<?php

namespace common\models\course;

use Yii;

/**
 * This is the model class for table "{{%course_order}}".
 *
 * @property int $id
 * @property string $order_no 课程订单号
 * @property string $price 课程费用（元）
 * @property string $discount 课程优惠费用（元）
 * @property string $user_id 用户ID
 * @property string $course_id 课程ID
 * @property string $teacher_id 课程讲师教师ID
 * @property string $school_id 学校ID
 * @property string $out_trade_no 交易支付订单号
 * @property string $pay 交易支付金额
 * @property string $pay_time 交易支付时间
 * @property int $status 状态
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property string $expired_at 交易过期时间
 * @property string $finished_at 订单完成时间
 */
class CourseOrder extends \common\base\ActiveRecord {

    use \common\traits\QueryInstanceActiveRecord;

    const STATUS_DEFAULT = 0;
    const STATUS_PAID = 1;
    const STATUS_FINISHED = 2;
    const STATUS_CANCEL = -1;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%course_order}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['price', 'discount', 'pay'], 'number'],
            [['user_id', 'course_id', 'pay_time', 'status', 'created_at', 'updated_at', 'expired_at', 'finished_at'], 'integer'],
            [['order_no', 'out_trade_no'], 'string', 'max' => 32],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'order_no' => '课程订单号',
            'price' => '课程费用（元）',
            'discount' => '课程优惠费用（元）',
            'user_id' => '用户ID',
            'course_id' => '课程ID',
            'out_trade_no' => '交易支付订单号',
            'pay' => '交易支付金额',
            'pay_time' => '交易支付时间',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'expired_at' => '交易过期时间',
            'finished_at' => '订单完成时间',
        ];
    }

    public function getIsPaid() {
        return $this->pay_time > 0 && $this->status >= self::STATUS_PAID && !($this->pay - $this->price + $this->discount);
    }

    public function fields() {
        return [
            'id',
            'order_no',
            'price',
            'discount',
            'user_id',
            'course_id',
            'out_trade_no',
            'pay',
            'pay_time',
            'status',
            'ispay' => 'isPaid',
        ];
    }

    public function getCourse() {
        return $this->hasOne(Course::className(), ['id' => 'course_id']);
    }

    public function generateOrderNo() {
        $date = date('Ymd');

        $rules = [
            'code' => "1" . rand(0, 9),
            'course' => str_pad(substr($this->user_id . $this->course_id, 0, 4), 4, "0", STR_PAD_LEFT),
            'month' => substr($date, 4),
        ];
        do {
            $micro = round((microtime(true) - strtotime($date)) * 10000);
            $rules['micro'] = str_pad($micro, 6, 0, STR_PAD_RIGHT);
            $tn = implode($rules);
            $record = static::find()->where(['order_no' => $tn])->exists();
        } while ($record);
        return $this->order_no = $tn;
    }

    public static function findByOrderNo($orderNo) {
        return static::findOne(['order_no' => $orderNo]);
    }

}
